package com.example.springboottest.example.rabbitmq.p2p;

import com.example.springboottest.base.AbstractService;
import com.example.springboottest.example.rabbitmq.RabbitUtil;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class RabbitMQReceiveNew extends AbstractService {
    public static String CLIENT_ID = "faw_fbom";
    public static String EXCHANGE_IDM = "idm_exchange";
    public static String QUEUE_NAME = "orgUserSync";
    public static String QUEUE_A = QUEUE_NAME + CLIENT_ID;
    public static String BASIC_ROUTING_KEY = "topic.idm.basic." + CLIENT_ID;
    public static String CONSUMER_TAG = "rabbit_faw_fbom";

    public static void main(String[] args) {
        new RabbitMQReceiveNew().init();
    }


    public void init() {
        ConnectionFactory factory = RabbitUtil.getConnectionFactory();
        Connection connection = null;
        Boolean autoAck = true;//自动确认消费，只要消费者从队列中获取到消息，服务器都认为消息已经成功被消费
        try {
            connection = factory.newConnection();//创建连接
            final Channel channel = connection.createChannel();//创建消息通道
            logger.info("QUEUE_A:\t" + QUEUE_A);
            //durable参数表示是否消息持久化   true表示rabbitMQ默认将消息存储在内存中，false表示持久化
            channel.queueDeclare(QUEUE_A, true, false, false, null);//声明消息队列
            channel.queueBind(QUEUE_A, EXCHANGE_IDM, BASIC_ROUTING_KEY);//绑定队列到交换机
            //设置为1表示同一时刻服务器只会发1条消息给消费者，只有消费者确认消费了这条消息，服务器才会发送下一条消息；如果设置为0，则没有限制，服务器会将所有消息尽快发送给消费者
            channel.basicQos(0);

            logger.info("成功连上RabbitMQ队列");
//            Consumer consumer = new DefaultConsumer(channel) {//进行消息的消费，重写handleDelivery()方法，加入业务代码
            channel.basicConsume(QUEUE_A, autoAck, CONSUMER_TAG, new DefaultConsumer(channel) {//进行消息的消费，重写handleDelivery()方法，加入业务代码
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope, BasicProperties properties,
                                           byte[] body) throws IOException {
                    try {
                        logger.info("接收到MQ队列推送-begin");

                        /**
                         * 执行业务方法
                         */
                        String message = new String(body, "UTF-8");//获取消息体
                        if (StringUtils.isNotEmpty(message)) {//消息不为空，执行业务代码
                            logger.info("message：{}", message);
                        }

                    } catch (Exception e) {
                        logger.error("接收到MQ队列推送失败：" + e.getMessage());
                        e.printStackTrace();
                    } finally {
                        logger.info("接收到MQ队列推送-end");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("rabbitMQ消费者监控服务启动失败，创建队列连接失败：" + e.getMessage());
        }
    }
}